Python学习笔记

您所在的位置:网站首页 python 函数自定义 Python学习笔记

Python学习笔记

2024-06-03 05:22| 来源: 网络整理| 查看: 265

一、函数

1、内建函数

输入dir(__builtins__)前后两个下划线,可以查看python异常名,属性名和内建函数;

输入help(函数名),可查看函数使用方法。

(1)常用内建函数

1)abs()

求一个数的绝对值。

>>> a=-10 >>> print(abs(a)) 10

2)divmod()

返回一个元组、同时计算商和余数。

>>> a,b=divmod(10,3) >>> print(a,b) 3 1

3)round()

对浮点数进行四舍五入,round有两个参数,第一个是要进行运算的值,第二个是要保留小数点后多少位。

>>> import math >>> for i in range(0,10): print(round(math.pi,i)) 3.0 3.1 3.14 3.142 3.1416 3.14159 3.141593 3.1415927 3.14159265 3.141592654

(2)字符串常用函数

1)join()

字符串合并和拆分,通过一个字符,将列表合并成字符串。

>>> b='-'#可以为任意字符 >>> a=['aa','bb','cc','dd'] >>> print(b.join(a)) aa-bb-cc-dd

2)split()

将一个字符串拆分成一个列表,要有相同特点才能拆分。

>>> a='aa-bb-cc-dd' >>> print(a.split('-')) ['aa', 'bb', 'cc', 'dd']

3)startwith()和endswith()

判定字符串的开头和结尾。

>>>a='hello world my name is hupo' >>>print(a.startwith('hel')) >>>print(a.endswith('world')) True False

4)strip()

去除字符串开头结尾的空格或制表符。

>>>a=' hello world' >>>print(a.strip()) hello world

5)ljust()、rjust()、center()

左对齐、右对齐和中间对齐。

>>> a='hello world' >>> print(a.ljust(20,'*'))#总长度20,不够用*来补足 hello world********* >>> print(a.rjust(20,'*')) *********hello world >>> print(a.center(20,'*')) ****hello world*****

6)find()

查找子串,返回的是要查询的子串的起始位置在字符串中的下标,如果返回-1,就代表找不到。

>>>a='hello world' >>>print(a.find('world')) 6

7)replace()

替换字串,字符串值不可变对象,只能生成新字符串。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3